﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using WAD.WEB.AppCode;
using System.IO;
using System.Net;
using GL.Tools;
using WAD.WEB.AppCode;

namespace WAD.WEB.Client2.Ajax
{
    /// <summary>
    /// Upload 的摘要说明
    /// </summary>
    public partial class Upload : AjaxBase
    {
        public override void AjaxMethodDispatch(String identity)
        {
            switch (identity)
            {
                case "img": this.Img(); break;
                case "wximg": this.WxImg(); break;
                case "jcropimg": this.JcropImg(); break;
            }
        }

        /// <summary>
        /// 上传图片
        /// </summary>
        [QD.Web.Ajax.AjaxMethod]
        public void Img()
        {
            String fn = StartUpload(WJXConfig.Path.IMAGE);//上传到服务器的图片路径
            bool isCut = Parse.Boolean("is_cut", false);//裁剪处理
            bool isCompress = Parse.Boolean("is_compress", false);//压缩处理

            int width = Parse.Int("width", 0);
            int height = Parse.Int("height", 0);

            if (isCut || isCompress)
            {
                if (width == 0 || height == 0)
                {
                    ParamError();
                }
            }
            else
            {
                Success(fn);
            }


            //图片处理
            //String serverPath = HttpContext.Current.Server.MapPath(fn);//服务器的完整路劲

            String serverPath = WJXConfig.Path.UPLOAD_DIR + fn;
            if (string.IsNullOrEmpty(WJXConfig.Path.UPLOAD_DIR))
                serverPath = HttpContext.Current.Server.MapPath(fn);    //服务器的完整路劲

            //生成新文件名
            String newPath = Path.GetDirectoryName(serverPath) + "/_" + Path.GetFileName(serverPath);

            bool flag = false;
            if (isCut)
            {
                flag = ImageUtil.Cut(serverPath, newPath, width, height, true);
            }
            else if (isCompress)
            {
                flag = ImageUtil.Compress(serverPath, newPath, width, height);
            }
            else
            {
                ;
            }

            if (flag)
            {
                try
                {
                    //删除原图
                    if (File.Exists(HttpContext.Current.Server.MapPath(fn)))
                        File.Delete(HttpContext.Current.Server.MapPath(fn));
                }
                catch (Exception e)
                {

                }

                //String url = newPath.Replace(HttpRuntime.AppDomainAppPath.ToString(), "/").Replace("\\", "/");
                //图片处理成功,返回图片相对路经
                Success(fn.Replace(Path.GetFileName(serverPath), "_" + Path.GetFileName(serverPath)));
            }
            else
            {
                Fail();
            }
        }
        /// <summary>
        /// 上传图片
        /// </summary>
        [QD.Web.Ajax.AjaxMethod]
        public void WxImg()
        {
            var url = Parse.String("url", "");

            var fn = WXStartUpload(url);//上传到服务器的图片路径
            bool isCut = Parse.Boolean("is_cut", false);//裁剪处理
            bool isCompress = Parse.Boolean("is_compress", false);//压缩处理

            int width = Parse.Int("width", 0);
            int height = Parse.Int("height", 0);

            if (isCut || isCompress)
            {
                if (width == 0 || height == 0)
                {
                    ParamError();
                }
            }
            else
            {
                Success(fn);
            }
            String serverPath = WJXConfig.Path.UPLOAD_DIR + fn;
            if (string.IsNullOrEmpty(WJXConfig.Path.UPLOAD_DIR))
                serverPath = HttpContext.Current.Server.MapPath(fn);    //服务器的完整路劲

            //生成新文件名
            String newPath = Path.GetDirectoryName(serverPath) + "/_" + Path.GetFileName(serverPath);

            bool flag = false;
            if (isCut)
            {
                flag = ImageUtil.Cut(serverPath, newPath, width, height, true);
            }
            else if (isCompress)
            {
                flag = ImageUtil.Compress(serverPath, newPath, width, height);
            }
            else
            {
                ;
            }

            if (flag)
            {
                try
                {
                    //删除原图
                    if (File.Exists(HttpContext.Current.Server.MapPath(fn)))
                        File.Delete(HttpContext.Current.Server.MapPath(fn));
                }
                catch (Exception e)
                {

                }

                //String url = newPath.Replace(HttpRuntime.AppDomainAppPath.ToString(), "/").Replace("\\", "/");
                //图片处理成功,返回图片相对路经
                Success(fn.Replace(Path.GetFileName(serverPath), "_" + Path.GetFileName(serverPath)));
            }
            else
            {
                Fail();
            }
        }
        /// <summary>
        /// 选框裁剪图片
        /// </summary>
        [QD.Web.Ajax.AjaxMethod]
        public void JcropImg()
        {
            int x = Parse.Int("x", 0);
            int y = Parse.Int("y", 0);
            int w = Parse.Int("w", 0);
            int h = Parse.Int("h", 0);
            int width = Parse.Int("width", 0);
            int height = Parse.Int("height", 0);

            String fn = StartUpload(WJXConfig.Path.IMAGE);//上传到服务器的图片路径
            String inPath = HttpContext.Current.Server.MapPath(fn);//服务器的完整路劲
            String outPath = Path.GetDirectoryName(inPath) + "/_" + Path.GetFileName(inPath); //生成新文件名

            if (ImageUtil.JcropImg(inPath, outPath, x, y, w, h, width, height))
            {
                Success(outPath.Replace(HttpRuntime.AppDomainAppPath.ToString(), "/").Replace("\\", "/"));
            }
        }


        /// <summary>
        /// 开始上传
        /// </summary>
        /// <param name="path"></param>
        private String StartUpload(String path)
        {
            //没有要上传的文件
            if (Context.Request.Files.Count < 1)
            {
                ParamError();
            }

            //上传的第一个文件
            HttpPostedFile httpFile = HttpContext.Current.Request.Files[0];

            //获取文件后缀
            string ext = Path.GetExtension(httpFile.FileName).ToLower();

            //文件名
            String name = UserId + "_" + DateTime.Now.ToString("yyyyMMddHHmmss") + StringHelper.Random(6) + ext;

            //Url访问的文件夹
            String urlDir = String.Empty;

            String dateStr = DateTime.Now.ToString("yyyy") + "/" + DateTime.Now.ToString("MM") + "/";

            path += dateStr;

            //绝对路径文件夹
            //String jdDir = HttpContext.Current.Server.MapPath(path);

            String jdDir = WJXConfig.Path.UPLOAD_DIR + path;
            if (string.IsNullOrEmpty(WJXConfig.Path.UPLOAD_DIR))
                jdDir = HttpContext.Current.Server.MapPath(path);

            //文件夹不存在创建文件夹
            if (!System.IO.Directory.Exists(jdDir))
            {
                System.IO.Directory.CreateDirectory(jdDir);
            }

            httpFile.SaveAs(jdDir + name);
            return path + name;
        }
        /// <summary>
        /// 开始上传
        /// </summary>
        /// <param name="path"></param>
        private string WXStartUpload(string url)
        {
            var file = string.Empty;
            var content = string.Empty;

            var savepath = string.Empty;
            
            //文件名
            String name = DateTime.Now.ToString("yyyyMMddHHmmss") + "-" + StringHelper.Random(6) + ".jpg";
            WebClient mywebclient = new WebClient();
            var path = WJXConfig.Path.IMAGE + DateTime.Now.ToString("yyyy") + "/" + DateTime.Now.ToString("MM") + "/";
            var jdDir = WJXConfig.Path.UPLOAD_DIR + path;
            if (string.IsNullOrEmpty(WJXConfig.Path.UPLOAD_DIR))
                jdDir = HttpContext.Current.Server.MapPath(path);
            //文件夹不存在创建文件夹
            if (!System.IO.Directory.Exists(jdDir))
            {
                System.IO.Directory.CreateDirectory(jdDir);
            }
            try
            {
                mywebclient.DownloadFile(url, jdDir + name);
            }
            catch (Exception ex)
            {
                Fail(ex.ToString());
            }
            return path + name;









        }
    }
}